import axios from 'axios';
import { Comment } from '../types';
import { API_PATHS, getAuthHeaders } from '../../../config/apiConfig';

export class CommentService {
  private static readonly API_BASE = API_PATHS.comments;

  static async addComment(postId: number, content: string): Promise<Comment> {
    // 获取当前用户信息 - 使用AuthService的存储键
    const currentUser = JSON.parse(localStorage.getItem('auth_user') || '{}');
    const userId = currentUser.id || Number(localStorage.getItem('userId'));
    
    if (!userId) {
      throw new Error('用户未登录');
    }
    
    // 使用本地时区格式化日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const commentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    
    try {
      console.log(`正在添加评论到帖子ID为${postId}，API路径: ${this.API_BASE}`);
      const response = await axios.post(
        this.API_BASE,
        {
          postId: Number(postId),
          userId: Number(userId),
          commentContent: content,
          commentTime
        },
        { headers: getAuthHeaders() }
      );
      console.log('添加评论成功:', response.data);
      
      // 确保返回的数据符合 Comment 接口的格式
      const commentData = response.data;
      
      // 如果服务器返回的数据格式不完整，我们需要手动补充
      return {
        commentId: commentData.commentId,
        postId: commentData.postId || Number(postId),
        userId: commentData.userId || Number(userId),
        username: commentData.username || currentUser.username || `用户${userId}`,
        commentContent: commentData.commentContent || commentData.content || content,
        commentTime: commentData.commentTime || commentData.createdAt || commentTime
      };
    } catch (error) {
      console.error('添加评论失败:', error);
      throw error;
    }
  }

  static async deleteComment(commentId: number): Promise<void> {
    await axios.delete(`${this.API_BASE}/${commentId}`, { headers: getAuthHeaders() });
  }

  static async getCommentsByPostId(postId: number): Promise<Comment[]> {
    // 确保 postId 是数字类型
    const postIdNumber = Number(postId);
    if (isNaN(postIdNumber)) {
      console.error('无效的帖子ID:', postId);
      return [];
    }
    
    // 根据后端 CommentController.java 的定义，正确的路径是 /post/{postId}
    const apiUrl = `${this.API_BASE}/post/${postIdNumber}`;
    console.log(`正在获取帖子ID为${postIdNumber}的评论，API路径: ${apiUrl}`);
    
    try {
      const response = await axios.get(apiUrl, { headers: getAuthHeaders() });
      console.log('获取评论成功:', response.data);
      
      // 转换评论数据格式
      const comments = (response.data || []).map((comment: any) => {
        return {
          commentId: comment.commentId,
          postId: comment.postId,
          userId: comment.userId,
          username: comment.username || `用户${comment.userId || '未知'}`, // 直接使用后端返回的username，如果没有则使用默认值
          commentContent: comment.commentContent,
          commentTime: comment.commentTime
        };
      });
      
      return comments;
    } catch (error) {
      console.error('获取评论失败:', error);
      // 返回空数组而不是抛出异常，避免整个应用崩溃
      return [];
    }
  }

  static async getCommentsByUserId(userId: number): Promise<Comment[]> {
    try {
      const response = await axios.get(`${this.API_BASE}/user/${userId}`, { headers: getAuthHeaders() });
      return response.data || [];
    } catch (error) {
      console.error(`获取用户ID为${userId}的评论失败:`, error);
      return [];
    }
  }
}